<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import resize from './mixins/resize'
import * as echarts from 'echarts/core';
import 'echarts/theme/macarons' // 引入主题

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: [String, Number],
      default: '280px'
    },
    chartData: {
      type: Array,
      required: true,
      default: () => [
        // { value: 320, name: '近一个月' },
        // { value: 240, name: '近两个月' },
        // { value: 149, name: '近三个月' },
        // { value: 100, name: '近四个月' },
        // { value: 59, name: '近五个月' }
      ]
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')

      // 创建颜色映射表
      const colorMap = {};
      this.chartData.forEach(item => {
        colorMap[item.name] = item.itemStyle?.color || null;
      });

      this.chart.setOption({
        // tooltip: {
        //   trigger: 'item',
        //   formatter: '{a} <br/>{b} : {c} ({d}%)'
        // },
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            // 获取当前项的颜色
            const color = params.color || '#333';
            return `<span style="display:inline-block;margin:2px 0;border-left:4px solid ${color};padding-left:6px;color:${color}">${params.seriesName}</span><br/>` +
              `<span style="color:${color}">● ${params.name} : ${params.value} (${params.percent}%)</span>`;
          }
        },
        legend: {
          show: false, // 隐藏图例
          left: 'center',
          bottom: '0',
          data: this.chartData.map(item => item.name),
          textStyle: {
            color: (name) => {
              return colorMap[name] || '#333'; // 默认颜色
            }
          }
        },
        series: [
          {
            name: '质保金待收',
            type: 'pie',
            roseType: false,
            radius: '80%',
            center: ['50%', '45%'],
            data: this.chartData,
            animationEasing: 'cubicInOut',
            animationDuration: 2600
          }
        ]
      })
    }
  }
}
</script>